﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using System.Text;
using System.Xml;
using System.IO;
using MLY.Bll;
using MLY.Dal;

namespace MLY.LTR
{
    public partial class addWoFile : Bll.BasePage
    {
        private bool mIsClient = false;
        private bool hasErrors = false;
        private string mResult = "";
        private string mFileName;

        #region Session Properties
        //------------------------

        private string FileTxt
        {
            get
            {
                return Session["fileTxt"] == null ? null : Session["fileTxt"].ToString();
            }
            set
            {
                Session["fileTxt"] = value;
            }
            
        }

        private string ImportFileName
        {
            get
            {
                return Session["ImportFileName"] == null ? "" : Session["ImportFileName"].ToString();
            }
            set
            {
                Session["ImportFileName"] = value;
            }
        }

        private List<Dal.TableCsvTemplateForUser> FieldsToAdd
        {
            get { return Session["fieldsToAdd"] == null ? null : (List<Dal.TableCsvTemplateForUser>)Session["fieldsToAdd"]; }
            set { Session["fieldsToAdd"] = value; }
        }

        private int TempalteIdSession
        {
            get { return Convert.ToInt32(Session["templateId"]); }
            set { Session["templateId"] = value; }
        }

        private List<Dictionary<string, object>> NewWoList
        {
            get
            {
                return Session["newWoList"] == null ? null : (List<Dictionary<string, object>>)Session["newWoList"];
            }
            set
            {
                Session["newWoList"] = value;
            }
        }

        //--------------------------=
        #endregion Session Properties

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (FieldsToAdd == null)
                    FieldsToAdd = new List<MLY.Dal.TableCsvTemplateForUser>();

                /// DEMO CODE
                //if (Session["UserId"].ToString() == "39")
                //{
                //    if ((string)Session["DemoStage"] == "DataTransfer")
                //    {
                //        FileUpload1.CssClass = "demohighlight";
                //        myWizard.NavigationButtonStyle.CssClass = "Btn smallBtn demohighlight";
                //        MLY.Bll.Demo.MoveToNextDemoSubStage();
                //    }
                //}
            }
            NewWoList = new List<Dictionary<string, object>>();
            if (Request.QueryString["isclient"] != null)
                mIsClient = true;

            BindFieldsToAddGrid();
            BindDelegates();

            templateSavePanel.Visible = false;
            ErrLbl.Text = "";

            if (templateIdHidden.Value != "")
                templateName.Text = Bll.clsCsvTemplate.getTemplateName(int.Parse(templateIdHidden.Value));

            LoadTemplates();
            if (!this.IsPostBack)
            {
                templateIdHidden.Value = DropDownList1.SelectedValue;
                itemToAddHidden.Value = "0";
            }


            ConfigCsvReceivedGrids();
            errMsgLbl.Text = "";

            if (SessParam.RoleId != 60)
            {
                delTemplateBtn.Visible = false;
            }
            else
            {
                delTemplateBtn.OnClientClick = "return confirm('" + Dictionary.Translate("clientAddWoFile.AreYouSureDeleteTemplate") + "')";
            }
        }

        private void BindFieldsToAddGrid()
        {
            fieldsToAddGrid.DataSource = FieldsToAdd;
            fieldsToAddGrid.DataBind();
        }

        private void BindDelegates()
        {
            delTemplateBtn.Click += new EventHandler(delTemplateBtn_Click);
            saveTemplateBtn.Click += new EventHandler(saveTemplateBtn_Click);
            DropDownList1.DataBound += new EventHandler(DropDownList1_DataBound);
            clearFieldsBtn.Click += new EventHandler(clearFieldsBtn_Click);
            myWizard.FinishButtonClick += new WizardNavigationEventHandler(myWizard_FinishButtonClick);
        }

        private void ConfigCsvReceivedGrids()
        {
            if (hasHeadersHidden.Value != "")
            {
                userCsvReceived.Visible = true;
                userCsvNoHeaders.Visible = false;
            }
            else
            {
                userCsvReceived.Visible = false;
                userCsvNoHeaders.Visible = true;
            }
        }

        private void LoadTemplates()
        {
            if (Session["userId"] != null)
            {
                DropDownList1.Items.Clear();
                // New Template
                DropDownList1.Items.Add(new ListItem(Dictionary.Translate("clientAddWoFile.newTemplate "), "0"));
                DropDownList1.DataSource = Bll.clsCsvTemplate.getTemplatesForUser(Session["userId"].ToString());
                DropDownList1.SelectedIndex = DropDownList1.Items.Count - 1;
                DropDownList1.DataBind();
            }
        }

        void delTemplateBtn_Click(object sender, EventArgs e)
        {
            if (templateIdHidden.Value != "0")
            {
                Bll.clsCsvTemplate.DeleteTemplate(int.Parse(templateIdHidden.Value));
                LoadTemplates();
            }
        }

        void myWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            Response.RedirectTo("~/LTR/");
        }

        void DropDownList1_DataBound(object sender, EventArgs e)
        {
            DropDownList1.SelectedIndex = DropDownList1.Items.Count - 1;
        }

        void clearFieldsBtn_Click(object sender, EventArgs e)
        {
            FieldsToAdd.Clear();
            BindGridsWithHeaders();
        }

        public List<Dal.TableCsvTemplateForUser> GetMappedTemplateColumn(int idx)
        {
            var y = Bll.clsCsvTemplate.GetTemplateFields(int.Parse(templateIdHidden.Value)).Where(S => S.CsvTemplate_FieldOrder == idx).ToList();
            return y;
        }

        private List<Dal.TableCsvTemplateForUser> GetAllTemplateColumn()
        {
            var y = Bll.clsCsvTemplate.GetTemplateFields(int.Parse(templateIdHidden.Value)).OrderBy(T => T.CsvTemplate_FieldOrder).ToList();
            return y;
        }

        public void AddTemplateClicked(object sender, EventArgs a)
        {
            List<MLY.Dal.TableCsvTemplateForUser> allCsvTemplates = FieldsToAdd;
            string newTemplateName = templateNameTxt.Text;
            try
            {
                templateIdHidden.Value = Bll.clsCsvTemplate.AddTemplate(newTemplateName, allCsvTemplates).ToString();
                LinqDataSource1.DataBind();
                FieldsToAdd.Clear();
                userCsvReceived.DataBind();
                userCsvNoHeaders.DataSource = GetAllTemplateColumn();
                userCsvNoHeaders.DataBind();
                fieldsToAddGrid.DataBind();
                templateName.Text = Bll.clsCsvTemplate.getTemplateName(int.Parse(templateIdHidden.Value));
                BindGridsWithHeaders();
                TempalteIdSession = int.Parse(templateIdHidden.Value);
            }
            catch (Exception ex)
            {
                ErrLbl.Text = ex.Message;
            }
        }

        void saveTemplateBtn_Click(object sender, EventArgs e)
        {
            try
            {
                Bll.clsCsvTemplate.validateCsvFieldsList(FieldsToAdd);
                templateSavePanel.Visible = true;
            }
            catch (Exception ex)
            {
                ErrLbl.Text = ex.Message;
            }
        }

        void FinishWizard()
        {
            myWizard.ActiveStepIndex = 2;
            int successFull = 0, updated = 0;
            // Return list of key fields for current template.
            List<string> keyFileds = LoadKeyFileds();
            for (int i = 0; i < NewWoList.Count; i++)
            {
                try
                {
                    Bll.woStatus currStatus = Bll.clsWorkOrder.InsertWoFromDictionaryFile(NewWoList[i], mIsClient, keyFileds);
                    if (currStatus == MLY.Bll.woStatus.inserted)
                    {
                        successFull++;
                    }
                    else
                        updated++;
                }
                catch (Exception ex)
                {
                    hasErrors = true;
                    mResult += String.Format("Deal No. {0} {1} Reason:{2}", i + 1, Dictionary.Translate("clientAddWoFile.DealFailed"), ex.Message);
                    mResult += "\n";
                }
                //finally
                //{
                //    mResult += "\n";
                //}
            }
            mResult += "\n";
            if (hasErrors)
            {
                HandleMsg(string.Format(@"WorkOrders Received Successfully:{0}" + Environment.NewLine +
                                        @"WorkOrders Received With Errors:  {1}" + Environment.NewLine +
                                        @"WorkOrders Updated:{2}", successFull, mResult, updated), true);
                AddUploadLog(successFull, updated, mResult, true);

            }
            else
            {
                HandleMsg(string.Format("WorkOrders Received Successfully:{0}" + Environment.NewLine +
                                        "WorkOrders Updated:{1}", successFull, updated), false);
                AddUploadLog(successFull, updated, mResult, false);
            }

            // Alerts - sending emails.
            //Utils.CheckAlerts();
            //Utils.SendPendingAlerts();
        }

        private void MakeFile(string fileTxt)
        {
            string directory = Server.MapPath("~") + @"\fileStorage\user" + Utils.currUserId;
            DirectoryInfo i = new DirectoryInfo(directory);
            if (!i.Exists)
                i.Create();
            StreamWriter sw = new StreamWriter(directory + @"\" + mFileName);
            sw.Write(fileTxt);
            sw.Close();
        }

        public void addFieldBtnClicked(object sender, EventArgs e)
        {
            using (Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext())
            {
                try
                {
                    int newOrder = int.Parse(itemToAddHidden.Value);
                    var newFieldId = newFieldDdl.SelectedValue;
                    Dal.Lookup_CsvField newField = dc.Lookup_CsvFields.Where(S => S.Idx == int.Parse(newFieldId)).FirstOrDefault();

                    MLY.Dal.TableCsvTemplateForUser x = new MLY.Dal.TableCsvTemplateForUser()
                    {
                        Lookup_CsvField = newField,
                        CsvTemplate_FieldOrder = newOrder,
                        templateId = int.Parse(templateIdHidden.Value),
                        MappedColName = itemToAddNameHidden.Value,
                        IsKey = IsKeyCheckBox.Checked,
                        FileColumnName = fieldIdxDdl.SelectedItem.Text                        
                    };
                    FieldsToAdd.Add(x);
                    fieldsToAddGrid.DataBind();
                }
                catch //(Exception ex)
                {
                    errMsgLbl.Text = "error in template!";
                }
                finally
                {
                    IsKeyCheckBox.Checked = false;
                }
            }
        }
        private void AddUploadLog(int _received, int _updated, string _errors, bool _isError)
        {
            
            int userid;
            if (int.TryParse(Session["userId"].ToString(), out userid))
            {
                TableUploadsLog log = new TableUploadsLog(); 
                
                log.errors = _errors;
                log.isError = _isError;
                log.received = _received;
                log.updated = _updated;
                log.UserId = userid;

                using (Dal.lqKbmDataContext dc = new MLY.Dal.lqKbmDataContext())
                {
                    dc.TableUploadsLogs.InsertOnSubmit(log);
                    dc.SubmitChanges();
                }
            }
        }

        // Return list of key fields for current template.
        private List<string> LoadKeyFileds()
        {
            int? templateId = null;
            List<string> keyFileds = new List<string>();
            if (templateIdHidden.Value != "0")
            {
                templateId = TempalteIdSession;
                if (templateId.HasValue)
                {
                    List<TableCsvTemplateForUser> templateFields = clsCsvTemplate.GetTemplateFields(templateId.Value);
                    foreach (TableCsvTemplateForUser templateField in templateFields)
                    {
                        if (templateField.IsKey.HasValue && templateField.IsKey.Value)
                            keyFileds.Add(templateField.Lookup_CsvField.CsvField_Name);
                    }
                }
            }
            // Write template id and hey fields to log file.
            Log.LogTemplate(templateId, keyFileds);
            return keyFileds;
        }

        // Save imported file (.csv) into database.
        private void ImportFile()
        {
            if (mIsClient)
                Log.WriteInfo("Import client file \"" + ImportFileName + "\"");
            else
                Log.WriteInfo("Import supplier file \"" + ImportFileName + "\"");


            if (NewWoList.Count == 0)
            {
                int? val = null;
                if (templateIdHidden.Value != "0")
                    val = TempalteIdSession;

                bool hasHeaders = hasHeadersHidden.Value == "" ? false : true;
                NewWoList = File_Parser.ParseCsv(FileTxt, val, hasHeaders);
            }

            // Return list of key fields for current template.
            List<string> keyFileds = LoadKeyFileds();

            int successFull = 0, updated = 0;
            for (int i = 0; i < NewWoList.Count; i++)
            {
                try
                {
                    woStatus newStatus = clsWorkOrder.InsertWoFromDictionaryFile(NewWoList[i], mIsClient, keyFileds);
                    if (newStatus == woStatus.inserted)
                        successFull++;
                    else
                        updated++;                    
                }
                catch (Exception ex)
                {
                    hasErrors = true;
                    string dealFailed = Dictionary.Translate("clientAddWoFile.DealFailed"); // Deal has Failed
                    mResult += String.Format("Deal No. {0} {1} Reason:{2}", i + 1, dealFailed, ex.Message);
                    mResult += "\n";
                }
                //finally
                //{
                //    mResult += "\n";
                //}
            }
            //mResult += "\n";

            // Alerts - checking what updates are needed
            //Utils.CheckAlerts();

            // Alerts - sending emails.
            //Utils.SendPendingAlerts();

            if (hasErrors)
            {
                HandleMsg(string.Format(@"WorkOrders Received Successfully:{0}" + Environment.NewLine +
                    @"WorkOrders Received With Errors:  {1}" + Environment.NewLine +
                "WorkOrders Updated:{2}", successFull, mResult, updated), true);
                AddUploadLog(successFull, updated, mResult, true);
            }
            else
            {
                HandleMsg(string.Format("WorkOrders Received Successfully:{0}" + Environment.NewLine +
                                         "WorkOrders Updated:{1}", successFull, updated), false);
                AddUploadLog(successFull, updated, mResult, false);
            }
            ImportFileName = "";
            
            
        }


        // Save imported file (.csv) into database.
        public void FinishStateActive(object sender, EventArgs e)
        {
            ImportFile();
            
            // demo Code
            if (Session["UserId"].ToString() == "39")
            {
                if ((string)Session["DemoStage"] == "DataTransfer")
                {
                    MLY.Bll.Demo.MoveToNextDemoSubStage();
                    (Master.FindControl("DemoLabel") as Label).Text =
                        Demo.Text((string)Session["DemoStage"], (string)Session["DemoSubStage"], "DemoLabel");
                    MLY.Bll.Demo.MoveToNextDemoStage();
                }
            }
            
        }

        public void fileUploadStep_Activate(object sender, EventArgs e)
        {
            // demo Code
            //if (Session["UserId"].ToString() == "39")
            //{
            //    if ((string)Session["DemoStage"] == "DataTransfer")
            //    {
            //        MLY.Bll.Demo.MoveToNextDemoSubStage();
            //        (Master.FindControl("DemoLabel") as Label).Text =
            //            Demo.Text((string)Session["DemoStage"], (string)Session["DemoSubStage"], "DemoLabel");                                        
            //    }
            //}
            
            TempalteIdSession = int.Parse(templateIdHidden.Value);
            StreamReader sr = null;
            
            // next string removed - IsClient is initialized at page load.
            //mIsClient = Request.QueryString["isclient"] != null ? true : false;
            try
            {
                logBox.Text = "";
                mFileName = FileUpload1.FileName;
                ImportFileName = Path.GetFileName(mFileName);

                if (FileUpload1.HasFile)
                {
                    if (!(mFileName.EndsWith("xml") || mFileName.EndsWith("csv")))
                        throw new Exception(Dictionary.Translate("clientAddWoFile.badFileType"));
                    sr = new StreamReader(FileUpload1.FileContent, Utils.currEncoding, true);
                }

                FileTxt = sr.ReadToEnd();

                // SAVE FILE
                MakeFile(FileTxt);

                // SAVE FILE
                if (mFileName.EndsWith("xml"))
                {
                    NewWoList = MLY.File_Parser.ParseXml(sr);
                    FinishWizard();
                }
                else
                {
                    if (hasHeadersHidden.Value != "")
                        BindGridsWithHeaders();
                    else
                    {
                        for (int i = 0; i < Utils.csvPaths.Length; i++)
                            fieldIdxDdl.Items.Add(new ListItem(i.ToString(), i.ToString()));
                        userCsvNoHeaders.DataSource = GetAllTemplateColumn();
                        userCsvNoHeaders.DataBind();
                    }
                    if (TempalteIdSession != 0)
                    {
                        NewTemplatePanel.Visible = false;
                        Label3.Visible = false;
                    }
                    else
                    {
                        NewTemplatePanel.Visible = true;
                        Label3.Visible = true;
                    }
                    
                }
            }
            catch (Exception ex)
            {
                HandleMsg(String.Format("File Error:{0}", ex.Message), true);
                myWizard.ActiveStepIndex = 0;
            }
        }

        private void BindGridsWithHeaders()
        {
            string[] headers = MLY.File_Parser.GetCsvHeaders(FileTxt);
            fieldIdxDdl.Items.Clear();
            for (int i = 0; i < headers.Length; i++)
            {
                fieldIdxDdl.Items.Add(new ListItem(headers[i], i.ToString()));
            }
            fieldsToAddGrid.DataBind();
            userCsvReceived.DataSource = headers;
            userCsvReceived.DataBind();
        }

        public void img_Click(object sender, ImageClickEventArgs e)
        {
            var fieldId = ((ImageButton)sender).CommandArgument;
            FieldsToAdd.Remove(FieldsToAdd.Where(S => S.CsvTemplate_FieldId.ToString() == fieldId).FirstOrDefault());
            BindFieldsToAddGrid();
        }

        public void TemplateColumns_RowEditing(object sender, GridViewEditEventArgs e)
        {
            throw new NotImplementedException();
        }

        protected void myBtn_Click(object sender, EventArgs e)
        {
        }

        // Shows message to user and logs it!
        private void HandleMsg(string Msg, bool isError)
        {
            logBox.Text += String.Format("{0} " + Environment.NewLine, Msg);
            tblLogger.AddLogEntry(Msg, isError);
        }

        //protected void WizardNextButtonClick(object sender, WizardNavigationEventArgs e)
        //{
        //    if (myWizard.ActiveStepIndex == 0)
        //    {
        //        if (EditTemplateCheckbox.Checked)
        //        {
        //            myWizard.ActiveStepIndex = 1;
        //        }
        //        else
        //        {
        //            ImportFile();
        //            myWizard.ActiveStepIndex = 2;
        //        }
        //    }
        //}
    }
}
